package top.ddandang.blog.bean;

import top.ddandang.blog.model.pojo.User;
import top.ddandang.blog.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;

/**
 * <p>
 * 配置 shiro 授权和认证
 * </p>
 *
 * @author D
 * @version 1.0
 * @date 2020/6/26 11:18
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("授权");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();
        log.info(currentUser.getPosition()+"职位");
        String position = "user";
        if(currentUser.getPosition()){
            position = "admin";
        }
        simpleAuthorizationInfo.addStringPermission(position);

        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("认证");
        UsernamePasswordToken userToken =(UsernamePasswordToken) authenticationToken;
        User user = userService.getUser(userToken.getUsername());
        log.info(String.valueOf(user));
        if(user == null) {
            return null;
        }
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
